<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      v-show="showSearch"
      :inline="true"
      label-width="68px"
    >
      <!-- <el-form-item label="店铺编号" prop="shopNo">
        <el-input
          v-model="queryParams.shopNo"
          placeholder="请输入店铺编号"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="店铺名称" prop="shopName">
        <el-input
          v-model="queryParams.shopName"
          placeholder="请输入店铺名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="Search"
          @click="handleQuery"
          v-hasPermi="['system:code:query']"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:code:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:code:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:code:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:code:export']"
          >导出</el-button
        >
      </el-col>

      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table
      v-loading="loading"
      :data="codeList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" prop="id" />
      <el-table-column label="店铺编号" prop="shopNo" />
      <el-table-column
        label="店铺名称"
        prop="shopName"
        :show-overflow-tooltip="true"
      />

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:code:edit']"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:code:remove']"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改编码配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="roleRef"
        :model="form.info"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="店铺名称" prop="shopName">
          <el-input
            v-model="form.info.shopName"
            @change="CreateShopCode(form.info.shopName)"
            placeholder="请输入店铺名称"
          />
        </el-form-item>
        <el-form-item label="店铺编号" prop="shopNo">
          <el-input
            disabled
            v-model="form.info.shopNo"
            placeholder="输入店铺名称自动生成编码"
          />
        </el-form-item>
        <el-form-item label="归属部门" prop="deptId">
          <el-tree-select
            v-model="form.info.deptId"
            :data="deptOptions"
            :props="{
              value: 'id',
              label: 'label',
              children: 'children',
              disabled: (data) => {
                if (data.children && data.children.length > 0) {
                  return true;
                } else {
                  return false;
                }
              },
            }"
            value-key="id"
            placeholder="请选择归属部门"
            check-strictly
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Code">
import {
  listCode,
  getCode,
  addCode,
  updateCode,
  delCode,
} from "@/api/system/code";
import { deptTreeSelect } from "@/api/system/user";
import { treeselect as menuTreeselect } from "@/api/system/menu";
import { pinyin } from "pinyin-pro";
const { proxy } = getCurrentInstance();

const codeList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const menuOptions = ref([]);

const deptOptions = ref([]);
const menuRef = ref(null);

const data = reactive({
  form: { info: {} },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    // shopNo: undefined,
    shopName: undefined,
  },
  rules: {
    shopName: [
      { required: true, message: "店铺名称不能为空", trigger: "blur" },
    ],
    shopNo: [{ required: true, message: "店铺编号不能为空", trigger: "blur" }],
    deptId: [{ required: true, message: "部门不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询编码列表 */
function getList() {
  loading.value = true;
  listCode(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    (response) => {
      codeList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    }
  );
}
/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then((response) => {
    deptOptions.value = response.data;
  });
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 删除按钮操作 */
function handleDelete(row) {
  const codeIds = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除ID为"' + codeIds + '"的数据项?')
    .then(function () {
      return delCode(codeIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "credits/departmentShop/export",
    {
      ...queryParams.value,
    },
    `店铺编码${new Date().getTime()}.xlsx`
  );
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 查询菜单树结构 */
function getMenuTreeselect() {
  menuTreeselect().then((response) => {
    menuOptions.value = response.data;
  });
}

/** 重置新增的表单以及其他数据  */
function reset() {
  if (menuRef.value != undefined) {
    menuRef.value.setCheckedKeys([]);
  }

  form.value = {
    info: {
      shopNo: undefined,
      shopName: undefined,
      deptId: undefined,
    },
  };
  proxy.resetForm("roleRef");
}
/**根据店铺名称生成编码 */

function CreateShopCode(val) {
  form.value.info.shopNo = `${pinyin(val, {
    pattern: "first",
    toneType: "none",
    type: "array",
  })
    .join("")
    .toUpperCase()}`;
}

/** 添加编码 */
function handleAdd() {
  reset();
  getMenuTreeselect();
  open.value = true;
  title.value = "添加编码";
}
/** 修改编码 */
function handleUpdate(row) {
  reset();
  const codeId = row.id || ids.value;
  getCode(codeId).then((response) => {
    form.value.info = response.data;
    title.value = "修改编码";
    open.value = true;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["roleRef"].validate((valid) => {
    if (valid) {
      if (form.value.info.id != undefined) {
        updateCode(form.value.info).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCode(form.value.info).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
getDeptTree();
getList();
</script>
